# -*- coding: utf-8 -*-

# Copyright (c) 2011, Sergey Karakovskiy, Nikolay Sohryakov
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of Yasker nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import logging
from google.appengine.api import memcache
from google.appengine.ext import db
from datetime import datetime
from time import strptime
from Keys import *


__author__ = 'Nikolay Sohryakov, Sergey Karakovskiy'
__copyright__ = 'Copyright 2011, Yasker'
__license__ = 'New BSD'
__email__ = 'Nikolay.Sohryakov+yasker@gmail.com, Sergey.Karakovskiy+yasker@gmail.com'

class Project(db.Model):
	p_id = db.StringProperty()				#Project ID
	title = db.StringProperty()				#Title (project name)
	description = db.TextProperty()			#Description
	eta = db.StringProperty()				#ETA(estimated time of arrival; estimation)
	tags = db.StringListProperty()			#A list of tags
	participants = db.StringListProperty()	#A list of the project participants

class Task(db.Model):
	p_id = db.ReferenceProperty(Project)	#Owner Project ID
	t_parent = db.SelfReferenceProperty()	#Task parent (like parent task)
	t_id = db.StringProperty()				#Task id (this task)
	title = db.StringProperty()				#Title
	description = db.TextProperty()			#Description
	start_date = db.DateProperty()          #Start date
	due_date = db.DateProperty()            #Due date
	eta = db.StringProperty()				#ETA(estimated time of arrival; estimation)
	tags = db.StringListProperty()			#A list of the tags
	owner = db.StringProperty()				#Who created this task
	assignee = db.StringProperty()			#Assignee
	priority = db.IntegerProperty()			#Priority
	completeness = db.IntegerProperty()		#Completeness(in percents)
	updated = db.DateProperty()			    #Last update time and date


class AuthorizedUsers(db.Model):
	users = db.StringListProperty()	#A list of authorized users


def get_authorized_users_list():
	"""
	Get a list of the authorized users. If list is not available -- creates one.
	"""
	users_list = AuthorizedUsers.get_or_insert(key_name=AUTHORIZED_USERS_LIST
	                                           , users=[]).users
	memcache.set(AUTHORIZED_USERS_LIST, users_list)
	return users_list

def add_authorized_user(user):
	"""
	Add an authorized user to the list. If list is not available -- creates one before.
	"""
	users_list = AuthorizedUsers.get_or_insert(key_name=AUTHORIZED_USERS_LIST
	                                           , users=[])
	users_list.users.append(user)
	users_list.put()
	memcache.set(AUTHORIZED_USERS_LIST, users_list)

def get_all_projects():
	"""
	Get a list of the projects. Each list element is a dict.
	"""
	projects = Project.all()
	result = []
	for project in projects:
		result.append({
			PROJECT_ID: project.p_id,
			TITLE: project.title,
			DESCRIPTION: project.description,
			ETA: project.eta,
			TAGS: project.tags,
			PARTICIPANTS: project.participants
		})
	return result

def add_project(project_dict):
	"""
	Add a new project.

	project_dict -- a dictionary of the project properties. All properties should be presented.
	"""
	try:
		#Each project has a key -- it's unique ID, that makes possible to increase a requests speed
		project_inst = Project(key_name=project_dict[PROJECT_ID])
		#PROJECT_ID is generated by client. It's uniqueness guaranteed, as time is specified in UTC format
		project_inst.p_id = project_dict[PROJECT_ID]
		project_inst.title = project_dict[TITLE]
		project_inst.description = project_dict[DESCRIPTION]
		project_inst.put()
	except:
		logging.error('Exception while adding a project')
		return False
	return True

def get_project_root_tasks(project_id):
	"""
	Get a list of the root(1st level) tasks of the project
	with ID == project_id
	"""
	tasks = Task.all()
	result = []
	for task in tasks:
		result.append({
			PROJECT_ID: task.p_id,
		    TASK_PARENT: task.t_parent,
		    TASK_ID: task.t_id,
		    TITLE: task.title,
		    DESCRIPTION: task.description,
		    START_DATE: task.start_date,
		    DUE_DATE: task.due_date,
		    ETA: task.eta,
		    TAGS: task.tags,
		    OWNER: task.owner,
		    ASSIGNEE: task.assignee,
		    PRIORITY: task.priority,
		    COMPLETENESS: task.completeness,
		    UPDATED: task.updated
		})

	return result

def add_task(task_dict):
	"""
	Add a new task.

	task_dict -- a dictionary of the project properties. All properties should be presented
	except of the TASK_PARENT property.
	"""
	logging.info("adding task")
	try:
		#Each task has a key -- it's unique ID, that makes possible to increase a requests speed
		task_inst = Task(key_name=task_dict[TASK_ID])
		task_inst.p_id = db.Key(task_dict[PROJECT_ID])
		task_inst.t_id = task_dict[TASK_ID]
		if task_dict[TASK_PARENT] is not None:
			task_inst.t_parent = db.Key(task_dict[TASK_PARENT])
		task_inst.title = task_dict[TITLE]
		task_inst.description = task_dict[DESCRIPTION]
		task_inst.start_date = task_dict[START_DATE]
		task_inst.due_date = task_dict[DUE_DATE]
		task_inst.eta = task_dict[ETA]
		task_inst.tags = task_dict[TAGS]
		task_inst.owner = task_dict[OWNER]
		task_inst.assignee = task_dict[ASSIGNEE]
		task_inst.priority = task_dict[PRIORITY]
		task_inst.completeness = task_dict[COMPLETENESS]
		task_inst.updated = task_dict[UPDATED]
		task_inst.put()
	except:
		logging.error('Exception while adding a task')
		return False
	return True

def update_project(project_dict):
	"""
	Update project details. If project does not exist -- returns False, True otherwise.
	"""
	project_inst = Project.get_by_key_name(key_names=project_dict[PROJECT_ID])
	if project_inst is None:
		return False

	#Iterate through all filled fields and update them in the model
	for key in project_dict.keys():
		setattr(project_inst, key, project_dict[key])

	project_inst.put()
	return True

def update_task(task_dict):
	"""
	Update task details. If task does not exist -- returns False, True otherwise.
	"""
	task_inst = Task.get_by_key_name(key_names=task_dict[TASK_ID])
	if task_inst is None:
		return False

	#Iterate through all filled fields and update them in the model
	for key in task_dict.keys():
		if key == TASK_PARENT:
			task_inst.t_parent = db.Key(task_dict[TASK_PARENT])
		else:
			setattr(task_inst, key, task_dict[key])

	task_inst.put()
	return True
